package com.project.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ExpendRecord;
import com.project.bean.OrderBean;
import com.project.entity.AlipayBean;
import com.project.mapper.IExpendRecordMapper;
import com.project.mapper.IOrderMapper;
import com.project.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付宝沙箱测试
 *
 * @author 小道仙
 * @date 2020年2月17日
 */
@RestController
public class PayController {
    private final String APP_ID = "2021000122673366";
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC6sD23kXCZCpgJYxaqGNx7k/DrkltuhFs+Y84tO7YWed757wYnMpsemecqrgf3KJbMbp+cyn4J+9lOVlvKUsuor1+LW8lO4pBWOgmsso6z9e7m7fhtEmWXu6jzMf5fAFpujCg3PrhKCIcNIzRFcgpTVjgQlSTiGSK//PPd0lJWSg0djYtnUuueXIJ9swbO9nB/5eoyUDAXyk90xaROuXVBvXju6p5HwWdxExTdjRvTzrjt8J8owwE0M/H+Pw7XT1Lujhn8/YMvkrGYsncktOLrK2r4+feT9RQp7i+TIY+UooBb9MJZ36J64a5eo9S/o0zUTFWnDX1hYaYVPEvk3LvRAgMBAAECggEBAKkytCzcNwWtkU/oq5DsSWADHDYVBqLqeFvaTvG2DXjfaZRx6sy509bvO5D1+6go9EtB841CBOt9g1y5biW31ncCwwBl5tSFCLXtkfkgN6+otKY9hYstQkA7x4rqg5WMl2lbw9MWGCaZBfWFM4nBKtSO7u8wjSYSC+mfE1K2nQMwO9fu0PS+2eBDps6h+lCJW3+BfHEXh3/EXg/A2Zx6cDb93pCzH8mLYz8dWTSy3BGVUGHd7HfcuZe7JwQ8ItPPxVn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NNnQH5+tXNZytA/ZmuXp1afh0KQJJlLN8sIVWSIhmheHOsVSFa3RQms6UY184J8CU2PY6Ce5WH0dAIZe9JZFm61nmqkszW0QH8xu23PJYBCszHsYOl2C7Dh9M89ZQmZUXS6E3eEVHoxPQBjvuMRbTVXK+UxrK67jyFfYojL3Cd8RiT2LjVyiUGnYcj9SB/n8x/e31sIhYeKZg9k0rmO+vMjK/tdECqjSf9bIwHwRxL+TqjKhp2iE9a4Epfu2emwjfyAlUXYy5RshOmvxsncsn/dTdOIlO14jrqht4HEfQkJfVUVkgdqEw4qu32pmj3F/cGkY2aQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
//    private final String NOTIFY_URL = "http://43.139.6.10:8888/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8888/returnUrl";

    @Autowired
    private PayService payService;

    @Autowired
    private IOrderMapper orderMapper;
    @Autowired
    private IExpendRecordMapper expendRecordMapper;

    /**
     * 阿里支付
     * @return
     * @throws AlipayApiException
     */
    @GetMapping(value = "toBuyByAli")
    public String alipay(
            @RequestParam("outTradeNo") String outTradeNo,
            @RequestParam("subject")  String subject,
            @RequestParam("totalAmount") Double totalAmount) throws AlipayApiException {
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        return payService.aliPay(alipayBean);
    }

    @RequestMapping(value = "/returnUrl")
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

//            System.out.println("商户订单号="+out_trade_no);
//            System.out.println("支付宝交易号="+trade_no);
//            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
            System.out.println("支付成功，将订单数据持久化的数据库");
            QueryWrapper<OrderBean> qw = new QueryWrapper<>();
            qw.eq("orderNum",out_trade_no);
            OrderBean orderBean = orderMapper.selectOne(qw);
            orderBean.setOrderStatus(1);
            orderMapper.updateById(orderBean);
            ExpendRecord expendRecord=new ExpendRecord();
            expendRecord.setModeOfPayment("1");
            expendRecord.setUserNum(orderBean.getUserNum());
            expendRecord.setMoney(orderBean.getTotalPrice());
            expendRecordMapper.insert(expendRecord);
            return "支付成功 " +
                           "<a  href='http://1.12.224.95/'>返回</a>";//跳转付款成功页面
        }else{
            return "no";//跳转付款失败页面
        }
    }



}
